//
//  GSDKComplatform.m
//  GameSDK
//
//  Created by Johnny on 2017/7/28.
//  Copyright © 2017年 Johnny. All rights reserved.
//

#import "GSDKComplatform.h"
#import "GSDKWelcomeViewController.h"
#import "GSDKServicesManager.h"
#import "YYKit.h"
#import "GSDKCommonMethod.h"
#import "GSDKActivityIndicatorView.h"
#import "GSDKSuspensionView.h"
#import "NSUserDefaults+Extension.h"
#import "GSDKComplatformBase.h"
#import "UIAlertView+Extension.h"
#import "UIViewController+Extension.h"
#import "GSDKMainViewController.h"
#import "GSDKUpdateDataController.h"
#import "GSDKIAPController.h"
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import "GSDKWebViewController.h"
#import <GoogleSignIn/GoogleSignIn.h>
#import "GSDKProduct.h"
#import "WXApi.h"
static GSDKInitConfigure * shared = nil;

@interface GSDKInitConfigure ()
@property (nonatomic) BOOL isShowLoadingView;
@property (nonatomic,retain) GSDKWelcomeViewController * welcomeVC;
@end

@implementation GSDKInitConfigure
/**
 初始化游戏配置类
 */
+ (GSDKInitConfigure *)shared {
    static dispatch_once_t pred;
    dispatch_once(&pred, ^{
        if (shared == nil) {
            shared = [[self alloc] init];
            shared.isShowLoadingView = NO;
            GSDKCOMMONMETHOD.language = GSDK_LANGUAGE_EN;
            [shared performSelector:@selector(start) withObject:nil afterDelay:0.001];
        }
    });
    return shared;
}

/**
 设置SDK语言，默认是英语
 
 @param language sdk语言
 */
- (void)setSDKLanguage:(_GSDK_LANGUAGE)languag {
    GSDKCOMMONMETHOD.language = languag;
}

/**
 如果自动获取不到游戏的ViewController，就手动添加游戏的ViewController
 
 @param viewController RootViewController
 */
- (void)setRootViewController:(id)viewController {
    GSDKCOMMONMETHOD.rootViewController = viewController;
}

/**
 显示loading界面
 */
- (void)showLoadingView {
    shared.isShowLoadingView = true;
}

- (void)setWXAppId:(NSString *)WXAppId wxSecret:(NSString *)WXsecret {
    GSDKCOMMONMETHOD.WXAppId = WXAppId;
    GSDKCOMMONMETHOD.WXsecret = WXsecret;
}

- (void)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[FBSDKApplicationDelegate sharedInstance] application:application
                             didFinishLaunchingWithOptions:launchOptions];
}

- (void)start {
    if (shared.isShowLoadingView) {
        self.welcomeVC = nil;
        self.welcomeVC = [GSDKWelcomeViewController show];
    }
    /*
     GSDKINITCONFIGURE.gid = @"100000";
     GSDKINITCONFIGURE.appKey = @"ee1f19eab2ad58b30a9cb7ade441d293";
     GSDKINITCONFIGURE.version = @"1.0.0";
     GSDKINITCONFIGURE.versionName
     */
    [WXApi registerApp:GSDKCOMMONMETHOD.WXAppId withDescription:@"中游平台"];
    
    //判断传值
    NSAssert(GSDKINITCONFIGURE.gid, @"gid为nil，请查看初始化是否对其进行赋值");
    NSAssert(GSDKINITCONFIGURE.appKey, @"appKey为nil，请查看初始化是否对其进行赋值");
    NSAssert(GSDKINITCONFIGURE.version, @"version为nil，请查看初始化是否对其进行赋值");
    NSAssert(GSDKINITCONFIGURE.versionName, @"versionName为nil，请查看初始化是否对其进行赋值");
    NSAssert([[NSBundle mainBundle] infoDictionary][@"channelID"], @"channelID为nil，请查看info.plist是否对其进行赋值");
    
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"GoogleService-Info" ofType:@"plist"];
    NSDictionary *dic = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
    NSAssert(dic, @"GoogleService-Info not found");
    NSAssert(dic[@"CLIENT_ID"], @"GoogleService-Info error, CLIENT_ID not found");
    [GIDSignIn sharedInstance].clientID = dic[@"CLIENT_ID"];
    if (GSDKCOMMONMETHOD.rootViewController == nil) {
        GSDKCOMMONMETHOD.rootViewController = [UIViewController getCurrentRootViewController];
    }
    
    [self activeDevice];
}

- (void)activeDevice {
    @weakify(self)
    GSDKActiveDeviceModel * model = [[GSDKActiveDeviceModel alloc] initWithToken:[GSDKCommonMethod getDeviceID]];
    [[GSDKServicesManager new] request:model andCompletionBlock:^(id responseObject) {
        @strongify(self)
        GSDKResActiveDeviceModel * model = [GSDKResActiveDeviceModel modelWithJSON:responseObject];
        if ([model.code isEqualToString: @"0"]) {
            GSDKCOMMONMETHOD.GSDKToken = model.token;
            [self menu];
        } else {
            [UIAlertView showAt:model.message];
        }
    }];
}

- (void)menu {
    @weakify(self)
    [[GSDKServicesManager new] request:[[GSDKGetMenuModel alloc] initWithToken:GSDKCOMMONMETHOD.GSDKToken] andCompletionBlock:^(id responseObject) {
        @strongify(self)
        NSString * json = [responseObject jsonStringEncoded];
        GSDKResMenuModel * model = [GSDKResMenuModel modelWithJSON:json];
        
        if ([model.code isEqualToString:@"0"]) {
            NSMutableArray<GSDKResToolbarModel*>* lists = [NSMutableArray new];
            for (NSDictionary * dic in responseObject[@"tool_bar"]) {
                GSDKResToolbarModel * toolbar = [GSDKResToolbarModel new];
                toolbar.name = [NSString stringWithFormat:@"%@", dic[@"name"]];
                toolbar.action = [NSString stringWithFormat:@"%@", dic[@"action"]];
                toolbar.src = [NSString stringWithFormat:@"%@", dic[@"src"]];
                toolbar.url = [NSString stringWithFormat:@"%@", dic[@"url"]];
                [lists addObject:toolbar];
            }
            model.tool_bar = lists;
            NSMutableArray<GSDKResTypeModel*>* tLists = [NSMutableArray new];
            for (NSDictionary * dic in responseObject[@"type"]) {
                GSDKResTypeModel * type = [GSDKResTypeModel new];
                type.name = [NSString stringWithFormat:@"%@", dic[@"name"]];
                type.icon = [NSString stringWithFormat:@"%@", dic[@"icon"]];
                type.type = [NSString stringWithFormat:@"%@", dic[@"type"]];
                [tLists addObject:type];
            }
            model.type = tLists;
            GSDKCOMMONMETHOD.menuModel = model;
            
            [self gameVersion];
        } else {
            [UIAlertView showAt:model.message];
        }
    }];
}

- (void)gameVersion {
    @weakify(self)
    [[GSDKServicesManager new] request:[[GSDKGameVersionModel alloc] init] andCompletionBlock:^(id responseObject) {
        @strongify(self)
        GSDKResGameVersionModel * model = [GSDKResGameVersionModel modelWithJSON:responseObject];
        [[GSDKUpdateDataController new] checkUpdate:model];
        [self initDataFinish];
    }];
}

- (void)initDataFinish {
    if (self.welcomeVC != nil) {
        [self.welcomeVC clean];
        self.welcomeVC = nil;
    }
    [GSDKCOMMONMETHOD online];
    [[NSNotificationCenter defaultCenter] postNotificationName:GSDKInitDidFinishNotification object:nil];

    [[GSDKIAPController shared] restored];
}

@end

static GSDKComplatform * cShared = nil;
@interface GSDKComplatform () <WXApiDelegate>
@property (nonatomic,retain) GSDKSuspensionView * bannerMenuView;
@end

@implementation GSDKComplatform
/**
 初始化游戏配置类
 */
+ (GSDKComplatform *)shared {
    static dispatch_once_t pred;
    dispatch_once(&pred, ^{
        if (cShared == nil) {
            cShared = [[self alloc] init];
        }
    });
    return cShared;
}

- (void)showSuspensionToolBar {
    if (!_bannerMenuView) {
        _bannerMenuView = [[GSDKSuspensionView alloc] initWithFrame: CGRectMake([GSDKCommonMethod getWidth] - 60, 40, 60, 60)];
        __weak GSDKComplatform * aself = self;
        _bannerMenuView.bannerMenuViewBlock = ^(NSInteger index) {
            if ([NSUserDefaults getValueIn:ISLOGIN] != nil) {
                [[NSNotificationCenter defaultCenter] postNotificationName:GSDKToolBarDidFinishNotification object:@YES userInfo:nil];
                [aself clickBannerMenuWithIndex:index];
            } else {
                [aself login];
            }
        };
    }
    if (GSDKCOMMONMETHOD.versionModel != nil) {
        if (GSDKCOMMONMETHOD.versionModel.is_tool_bar != nil) {
            if ([GSDKCOMMONMETHOD.versionModel.is_tool_bar isEqualToString:@"1"]) {
                [[UIViewController getCurrentRootViewController].view addSubview:_bannerMenuView];
            }
        }
    }
}

- (void)hideSuspensionToolBar {
    if (_bannerMenuView) {
        [_bannerMenuView removeFromSuperview];
    }
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    if ([url.absoluteString rangeOfString:@"fb"].length > 0) {
        BOOL handled = [[FBSDKApplicationDelegate sharedInstance] application:application
                                                                      openURL:url
                                                            sourceApplication:sourceApplication
                                                                   annotation:annotation
                        ];
        // Add any custom logic here.
        return handled;
    } else if ([url.absoluteString rangeOfString:@"com.googleusercontent"].length > 0) {
        BOOL handled = [[GIDSignIn sharedInstance] handleURL:url sourceApplication:sourceApplication
                                                  annotation:annotation];
        // Add any custom logic here.
        return handled;
    } else if ([sourceApplication isEqualToString:@"com.tencent.xin"]) {
        return [WXApi handleOpenURL:url delegate:self];
    }
    return NO;
}

/**
 *  点击悬浮窗展开后里面的按钮
 *
 *  @param index 展开后对应的按钮
 */
- (void)clickBannerMenuWithIndex:(NSInteger)index {
    dispatch_async(dispatch_get_main_queue(), ^{
        [[UIViewController getCurrentRootViewController].view setUserInteractionEnabled:NO];
        if (GSDKCOMMONMETHOD.menuModel.tool_bar.count == 1) {
            GSDKWebViewController * vc = [GSDKWebViewController new];
            GSDKWebModel * wModel = [[GSDKWebModel alloc] initIAPCallBackWithSid:GSDKCOMMONMETHOD.GSDKSid == nil ? GSDKCOMMONMETHOD.GSDKSid : @"" andToken:GSDKCOMMONMETHOD.GSDKToken andLogin_token: GSDKCOMMONMETHOD.accountModel.token];
            NSString * urlString = GSDKCOMMONMETHOD.menuModel.tool_bar[index].url;
            if (![urlString hasSuffix:@"?"]) { urlString = [NSString stringWithFormat:@"%@?", urlString]; }
            [vc reloadAtUrl: [NSString stringWithFormat:@"%@%@", urlString, [wModel getUrlParameter]]];
            [[UIViewController getCurrentRootViewController] presentViewController:vc animated:true completion:nil];
        } else {
            GSDKMainViewController * main = [[GSDKMainViewController alloc]initWithNibName:nil bundle:nil];
            main.selectedIndex = index;
            [[UIViewController getCurrentRootViewController] presentViewController:main animated:YES completion:nil];
        }
    });
}

- (void)onResp:(BaseResp *)resp {
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        SendAuthResp * sendResp = (SendAuthResp*)resp;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"wechatHandleNotificationName" object:sendResp];
    }
}

@end
